﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.Utilities;
using SaleDiscount.Portal.Common;
using SaleDiscount.Portal.Service;
using SaleDiscount.Portal.eBay;
using eBay.Service.Core.Soap;

namespace SaleDiscount.Portal
{
    public partial class ChooseListing : SaleDiscountPageBase
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                CancelButton = btnCancel;

                LoadDropDownLists();
                LoadActiveListings();

            }
        }

        private void LoadDropDownLists()
        {

          ddlListingFormat.Items.Add(ListingTypeCodeType.FixedPriceItem.ToString());
          ddlListingFormat.Items.Add(ListingTypeCodeType.Auction.ToString());
          ddlSortBy.Items.Add(new ListItem("Highest Priced", ItemSortTypeCodeType.CurrentPriceDescending.ToString()));
          ddlSortBy.Items.Add(new ListItem("Lowest Priced", ItemSortTypeCodeType.CurrentPrice.ToString()));
          ddlSortBy.Items.Add(new ListItem("Ending First", ItemSortTypeCodeType.EndTime.ToString()));
          ddlSortBy.Items.Add(new ListItem("Newly Listed", ItemSortTypeCodeType.StartTimeDescending.ToString()));
        }

        protected ItemInfoCriteria GetSearchCriteria()
        {
            var criteria = new ItemInfoCriteria
            {

            };

            //criteria.keyword = this.txtKeywords.Text.Trim();
            //criteria.StoreCategoryId = ddlStoreCategory.SelectedValue;
            criteria.ItemFormat = ddlListingFormat.SelectedValue;
            //criteria.CurrentPrice =new Range<decimal?>(txtPriceStart.Text.ToDecimal(),txtPriceEnd.Text.ToDecimal());
            criteria.SortBy = ddlSortBy.SelectedValue;
      
            return criteria;
        }
        private void LoadActiveListings()
        {
            var service = new SaleDiscountService();
            //todo

            this.grdInvoiceOrder.DataSource = service.LoadActiveListings(GetSearchCriteria(), false);
            this.grdInvoiceOrder.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            LoadActiveListings();
        }

        protected void grdInvoiceOrder_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var entity = (e.Row.DataItem);

                e.Row.Attributes["ItemId"] = Convert.ToString(DataBinder.Eval(entity, "ItemId"));


            }
        }


        public IList<ItemInfo> CheckItemSelection()
        {
            var selectedUsers = new List<ItemInfo>();

            foreach (GridViewRow row in grdInvoiceOrder.Rows)
            {
                var chkSelected = (CheckBox)row.FindControl("chkSelect");
                if (chkSelected != null)
                {
                    if (chkSelected.Checked)
                    {
                        var id = row.Attributes["ItemId"];
                       
                        selectedUsers.Add(new ItemInfo()
                        {
                            ItemId = id,
                   
                        });
                    }
                }
            }


            return selectedUsers;
        }

        protected void btnChoose_Click(object sender, EventArgs e)
        {
            var seletedItems = CheckItemSelection();
            if (seletedItems.Count > 0)
            {
                var items = new ItemInfoSelection()
                {
                    ItemIds = seletedItems.Select(o => o.ItemId.ToString()).Aggregate((a, b) => a + "," + b),
                 

                };
                var serializer = new DataContractJsonSerializer(typeof(ItemInfoSelection));
                var stream = new MemoryStream();
                serializer.WriteObject(stream, items);
                stream.Position = 0;
                var sr = new StreamReader(stream);
                string resultStr = sr.ReadToEnd();
                sr.Close();
                stream.Close();
                CloseWindow(resultStr);
            }
            else
            {
                base.Alert("please choose at least one item.");
                return;
            }

        }


        protected string GetImageUrl(object id)
        {
            if (MiscUtilities.IsNullOrEmpty(id)) return string.Empty;
            return id.ToString();
        }

        protected string GeItemFormatImageUrl(object id)
        {
            if (MiscUtilities.IsNullOrEmpty(id)) return string.Empty;
            var defaultImageUrl = "~/Images/ebay/iconFixedprice_16x16.gif";

            if (id.ToString() == ListingTypeCodeType.Chinese.ToString()) return "~/Images/ebay/iconAuction_16x16.gif";
            return defaultImageUrl;

        }

        protected string GetItemTitle(object itemId, object title)
        {
            var viewItemUrl = ApiContextLoader.LoadAppConfig("ViewItemUrl");
            var titleLink ="<a href='{0}'>{1}</a>";
            return titleLink.Formato(viewItemUrl.Formato(itemId),title) + "<br/>" + itemId;
        }

       
    }

    [DataContract]
     public class ItemInfoSelection
     {
        [DataMember]
         public string ItemIds { get; set; }
     }

}